<template>
  <div>
    <ListTab v-model="activeId" :show-header="!showMobilePage" :tabs="tabList" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="product-container min-fill-page">
      <dataDisplay
        v-loading="statisticsLoading"
        :data-list="statistDataList"
        class="mobile-data"
        style="margin-bottom:16px;"
      />
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          v-model="filterInput"
          :filter-list="filterList"
          :is-show-filter="isShowFilter"
          show-search-btn
          class="FilterTool"
          is-show-config
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="opeator-bar">
          <div v-if="canImport" class="btn-right">
            <el-button type="info" size="small" @click="goFreshOrder">订单更新</el-button>
          </div>
        </div>
      </div>
      <div v-if="isInitArchive && activeId === '已归档'" class="init-archive">
        <img :src="tip" class="tip">
        <p>{{ dataTip }}</p>
        <p>{{ searchTip }}</p>
      </div>
      <div v-else class="table-list">
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="listData.items.length"
            :data="listData.items"
            :ref="tableRefName"
            :row-class-name="tableRowClassName"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            element-loading-text="加载中..."
            empty-text="暂无数据"
            class="fb-table"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @sort-change="sortMethod"
            @select-all="selectTable">
            <u-table-column
              fixed="left"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column
              v-for="(titleItem, tIndex) in listData.titles"
              :key="titleItem + tIndex"
              :label="titleItem"
              :prop="titleItem"
              :fixed="titleItem === '操作'? 'right' : (titleItem==='订单号'?'left':(titleItem==='关联商品状态'?'right':false))"
              :min-width="minWidthSet(titleItem)"
              :width="titleItem === 'goodsId'? '1' : 'auto' "
              :class-name="titleItem === 'goodsId'? 'display-none' : '' "
              :sortable="sortable(titleItem)"
              :align="isPriceKeyword(titleItem)?'right':'left'"
            >
              <template slot-scope="scope">
                <div v-if="scope.column.label === '供货价（人工）'">
                  <PriceColumn :real-val="scope.row[tIndex]" :price="Number(scope.row[tIndex])" class="green" />
                </div>
                <div v-else-if="isSecretColumn(scope.column.label)">
                  <SecretText :log-text="getLogText(scope.row, scope.column)" :origin-text="scope.row[tIndex]" />
                </div>
                <div v-else-if="scope.column.label === '有赞成本价'">
                  <PriceColumn :class="Number(scope.row[tIndex]) === Number(scope.row[getTitleIndex('商品编码')])? 'green' : 'red'" :real-val="scope.row[tIndex]" :price="Number(scope.row[tIndex])" />
                </div>
                <div v-else-if="includesPriceField(titleItem)">
                  <PriceColumn :real-val="scope.row[tIndex]" :price="Number(scope.row[tIndex])" />
                </div>
                <div v-else-if="scope.column.label === '操作'" class="flex">
                  <template v-if="canEdit">
                    <div v-if="!scope.row[scope.row.length - 1]" style="margin-right:10px;" class="button-text" @click="goodsBatchConfirm(scope.row[0].trim(), scope.row)">关联</div>
                    <div v-if="!!scope.row[scope.row.length - 1] && scope.row[scope.row.length - 1].trim()" class="button-text" @click="goodsBatchConfirm(scope.row[0].trim(), scope.row)">编辑</div>
                  </template>
                  <!-- <el-dropdown v-if="canEdit">
                    <div class="el-dropdown-link">
                      <img :src="setting" alt="操作">
                    </div>
                    <el-dropdown-menu
                      slot="dropdown"
                      class="dropdown-wrap">
                      <el-dropdown-item v-if="!scope.row[scope.row.length - 1]" @click.native="goodsBatchConfirm(scope.row[0].trim(), scope.row)">
                        <div>待确认</div>
                      </el-dropdown-item>
                      <el-dropdown-item v-if="!!scope.row[scope.row.length - 1] && scope.row[scope.row.length - 1].trim()" @click.native="goodsBatchConfirm(scope.row[0].trim(), scope.row)">
                        <div>修改</div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
                </div>
                <div v-else-if="scope.column.label === '商品发货状态' || scope.column.label === '订单商品状态'" class="flex">
                  <StatusText
                    :color="(scope.row[tIndex] === '未发货' || scope.row[tIndex] === '待发货') ? '#FD8546' : '#31CC9C'"
                    :text="scope.row[tIndex]" />
                </div>
                <div v-else-if="scope.column.label === '关联商品状态'" class="flex">
                  <span v-if="scope.row[tIndex] === '已关联'" class="dot" style="background-color: rgb(49, 204, 156);"/>
                  <span v-else class="dot" style="background-color: rgb(153, 153, 153);"/>
                  <el-tooltip v-if="scope.row[tIndex] || scope.row[tIndex] === 0" placement="top">
                    <div slot="content" style="max-width:300px">{{ scope.row[tIndex] }}</div>
                    <div class="overflow" style="display:inline-block;max-width:100%;">
                      <span v-if="scope.row[tIndex] === '已关联'" style="color: #666">{{ scope.row[tIndex] }}</span>
                      <span v-else>{{ scope.row[tIndex] }}</span>
                    </div>
                  </el-tooltip>
                  <div v-else>--</div>
                </div>
                <div v-else style="width:100%;" class="flex">
                  <el-tooltip v-if="scope.row[tIndex] || scope.row[tIndex] === 0" placement="top">
                    <div slot="content" style="max-width:300px">{{ scope.row[tIndex] }}</div>
                    <div class="overflow" style="display:inline-block;max-width:100%;">{{ scope.row[tIndex] }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else-if="!listData.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="listData.total > 0"
            :current-page="listData.page"
            :page-size="listData.perPage"
            :total="listData.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-row>
        <fixed-pagination v-show="listData.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              v-model="filterInput"
              :filter-list="filterList"
              :is-show-filter="isShowFilter"
              show-search-btn
              class="FilterTool"
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus"/>
            <MoreOpeator
              v-if="canExport || canEdit"
              ref="moreOpeatorRef"
              :list="[
                {label: '导出订单', type: 'export', exportApi:'admin/commerce/productOrder/export', exportName:'导出订单',isBeforeExport:true, beforeExport: exportBeforeExport, refName:'projectExportRef', auth: canExport},
                {label: '商品确认', handelClick: goodsBatchConfirm, auth: canEdit},
                {label: '自动关联', handelClick: autoAssociation, auth: canEdit}
              ]"
              label="批量操作"
              show-mobile-icon
            />
            <createBtn v-if="canImport" text="订单更新" mobile-table @click.native="goFreshOrder"/>
          </template>
          <template v-else>
            <div class="button-container" style="display:flex;align-items:center;flex:1;">
              <MoreOpeator
                v-if="canExport || canEdit"
                ref="moreOpeatorRef"
                :list="[
                  {label: '导出订单', type: 'export', exportApi:'admin/commerce/productOrder/export', exportName:'导出订单',isBeforeExport:true, beforeExport: exportBeforeExport, refName:'projectExportRef', auth: canExport},
                  {label: '商品确认', handelClick: goodsBatchConfirm, auth: canEdit},
                  {label: '自动关联', handelClick: autoAssociation, auth: canEdit}
                ]"
                label="批量操作"
                style="margin-right:10px;"
              />
              <SelectionNum :select-item="multipleSelectionAll" style="margin-left:10px;" @clearMixinSelection="clearMixinSelection" />
            </div>
            <el-pagination
              :current-page="listData.page"
              :page-size="listData.perPage"
              :total="listData.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
    <GoodsConfirmDialog
      :dialog-form-visible="dialogGoodsConfirmVisible"
      :data="orderItem"
      :titles="listData.titles"
      :goods-id="goodsId"
      :specification-code-id="specificationCodeId"
      :order-nums="selectOrderNums"
      @close="closeDialog()"
      @success="handleSuccess()"/>
    <el-dialog
      :visible.sync="associationVisible"
      width="400px"
      center
      class="task-dialog"
      @close="associationVisible = false">
      <img :src="task" alt="task" >
      <div class="task-message">{{ associationMessage }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="associationVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import setting from '@/assets/setting.png';
import icon_6 from '@/assets/dataDisplay/icon_6.png';
import icon_7 from '@/assets/dataDisplay/icon_7.png';
import icon_8 from '@/assets/dataDisplay/icon_8.png';
import icon_9 from '@/assets/dataDisplay/icon_9.png';
import tip from '@/assets/orderlist/tip.png';
import task from '@/assets/orderlist/task.png';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ImportButton from './model/ImportBtn';
import ListTab from '@/components/ListTab';
import GoodsConfirmDialog from '@/components/Commerce/goodsConfirmDialog';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import { getOrderList, getCommerceStatistics, getGoodsOrderStatus, autoAssociation } from '@/api/commerce';
import { format } from '@/filters/date';
import { isNumberEmpty, moneyFilter } from '@/filters/number';
import { mapState } from 'vuex';
import axios from 'axios';
import createBtn from '@/components/Common/baseComponent/createBtn';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';

/**
 * getTitleIndex 根据 标题 获取 listData中的 title的索引 用来获取对应数据 ， 所以 已和产品约定好title名称不能
 * **/
export default {
  filters: {
    format,
    moneyFilter,
    isNumberEmpty
  },
  components: {
    Title,
    EmptyPlaceholder,
    ImportButton,
    ListTab,
    GoodsConfirmDialog, dataDisplay, MoreOpeator, createBtn
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      setting,
      icon_6,
      icon_7,
      icon_8,
      icon_9,
      tip,
      task,
      sortType: '',
      sortName: '',
      tabList: [],
      activeId: '全部',
      listLoading: false,
      statisticsLoading: false,
      screenWidth: document.body.clientWidth,
      listData: {
        items: [],
        isInit: true
      },
      page: 1,
      perPage: 20,
      isShowFilter: false,
      filterInput: {
        supplierName: ''
      },
      orderStatistics: {},
      uploadParams: {},
      tableRefName: 'goodsOrderTableRef', // 表格的ref名称
      idKey: 0, // 唯一表示字段
      ids: '',
      goodsId: '',
      specificationCodeId: '',
      specificationCodeIdLists: '',
      selectList: [], // 列表已选字段
      orderItem: [],
      dialogGoodsConfirmVisible: false,
      selectOrderNums: '',
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStart',
        end: 'createEnd',
        type: 'time'
      }, {
        attr: 'payTime',
        start: 'payStartTime',
        end: 'payEndTime',
        type: 'time'
      }, {
        attr: 'dealTime',
        start: 'dealStartTime',
        end: 'dealEndTime',
        type: 'time'
      }, {
        attr: 'goodTime',
        start: 'deliverGoodStart',
        end: 'deliverGoodEnd',
        type: 'time'
      }],
      isUmyTable: true,
      isInitArchive: false,
      lastArchivedTime: null,
      cancelDataToken: null,
      cancelStatisticsToken: null,
      associationVisible: false,
      associationMessage: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        { keyword: 'orderNum', name: '订单编号', labelWidth: '100px', type: 'input' },
        { keyword: 'goodsName', name: '商品名称', labelWidth: '100px', type: 'input' },
        { keyword: 'supplierName', name: '供应商名称', labelWidth: '100px', type: 'input' },
        { keyword: 'specificationCode', name: '规格编码', labelWidth: '100px', type: 'input' },
        { keyword: 'specificationId', name: '商品规格ID', labelWidth: '100px', type: 'input' },
        { keyword: 'goodsId', name: '商品ID', labelWidth: '100px', type: 'input' },
        { keyword: 'goodsSpecification', name: '商品规格', labelWidth: '100px', type: 'input' },

        { keyword: 'orderType', name: '订单类型', labelWidth: '100px', type: 'select', options: [
          { value: '自营订单', label: '自营订单' },
          { value: '分销订单', label: '分销订单' },
          { value: '供货订单', label: '供货订单' }
        ] },
        { keyword: 'goodsType', name: '商品类型', type: 'select', options: [
          { value: '普通商品', label: '普通商品' },
          { value: '分销商品', label: '分销商品' }
        ] },
        { keyword: 'goodsBelong', name: '商品归属', type: 'select', options: [
          { value: '采销型', label: '采销型' },
          { value: '服务型', label: '服务型' }
        ] },
        { keyword: 'goodsTypeYouZan', name: '订单类型(有赞)', type: 'select', className: 'filter-tool-width140', options: [
          { value: '分销供货订单', label: '分销供货订单' },
          { value: '分销买家订单', label: '分销买家订单' },
          { value: '分销买家订单/拼团订单', label: '分销买家订单/拼团订单' },
          { value: '积分兑换订单', label: '积分兑换订单' },
          { value: '拼团订单', label: '拼团订单' },
          { value: '普通订单', label: '普通订单' }
        ] },
        { keyword: 'relateGoodStatus', name: '关联商品状态', type: 'select', className: 'filter-tool-width140', options: [
          { value: '全部', label: '全部' },
          { value: '已关联', label: '已关联' },
          { value: '待关联', label: '待关联' }
        ] },
        { keyword: 'costVariance', name: '成本差异', type: 'select', options: [
          { value: '全部', label: '全部' },
          { value: '一致', label: '一致' },
          { value: '差异', label: '差异' }
        ] },
        { keyword: 'createTime', name: '订单创建时间', type: 'rangeDate', format: 'yyyy/MM/dd HH:mm:ss', monthSpan: this.activeId === '已归档' ? 6 : null, labelWidth: '100px' },
        { keyword: 'payTime', name: '买家付款时间', type: 'rangeDate', format: 'yyyy/MM/dd HH:mm:ss', monthSpan: this.activeId === '已归档' ? 6 : null, labelWidth: '100px' },
        { keyword: 'dealTime', name: '交易成功时间', type: 'rangeDate', format: 'yyyy/MM/dd HH:mm:ss', monthSpan: this.activeId === '已归档' ? 6 : null, labelWidth: '100px' },
        { keyword: 'goodTime', name: '商品发货时间', type: 'rangeDate', format: 'yyyy/MM/dd HH:mm:ss', monthSpan: this.activeId === '已归档' ? 6 : null, labelWidth: '100px' }
      ];
    },
    statistDataList() {
      const dataList = [
        { data: this.orderStatistics.totalOrder, label: '订单数', icon: icon_6, isMoney: false },
        { data: this.orderStatistics.totalPrice, label: '订单金额', icon: icon_7 },
        { data: this.orderStatistics.income, label: '收入', auth: this.showIncome, icon: icon_8 },
        { data: this.orderStatistics.unRelateOrder, label: '待关联订单', isMoney: false, tooltip: '未关联商品的订单数量', icon: icon_9 }
      ];
      return this.showIncome ? dataList : dataList.filter(data => data.label !== '收入');
    },
    activeName() {
      const item = this.tabList.find(i => i.id === this.activeId);
      return item ? item.name : '全部';
    },
    dataTip() {
      return `已归档数据为有赞订单的2020-11-20 00:00:00至${this.lastArchivedTime || '--'}的全部数据`;
    },
    searchTip() {
      return `注意：由于数据量过大，选择准确的时间范围后才可以查看到数据（订单创建时间、买家付款时间、交易成功时间、商品发货时间均可）`;
    },
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    canImport() {
      return (hasRouteAuth('crm:goodsOrder:import') || this.isAdmin) && this.activeId !== '已归档';
    },
    canExport() {
      return hasRouteAuth('crm:goodsOrder:export') || this.isAdmin;
    },
    canEdit() {
      return hasRouteAuth('crm:goodsOrder:edit') || this.isAdmin;
    },
    showIncome() {
      return this.activeName === '全部' || this.activeName === '已完成';
    },
    tableOutsideHeight() {
      return 246;
    }
  },
  created() {
    const { supplierName } = this.$route.query;
    if (supplierName) {
      this.filterInput.supplierName = supplierName;
      this.isShowFilter = true;
    }
    this.getTabList();
    const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
    if (!hasDefaultPresetFilter) {
      this.getData();
    }
  },
  methods: {
    hasRouteAuth,
    // 通过标题名称获取索引
    getTitleIndex(title) {
      if (!this.listData.titles) return '';
      const index = this.listData.titles.indexOf(title);
      if (index >= 0) {
        return index;
      }
      return '';
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.getData(false, true);
    },
    isSecretColumn(titleItem) {
      return ['收货人手机号/提货人手机号', '收货人省份', '收货人城市', '收货人地区', '详细收货地址/提货地址'].includes(titleItem);
    },
    minWidthSet(titleItem) {
      const map = {
        '操作': 80, '供货价（人工）': 170, '供货价(人工)': 170, '关联商品状态': 110,
        '订单类型': 100, '商品类型': 110, '商品退款状态': 110,
        '商品实际成交金额': 170, '商品已退款金额': 150, '运费': 100,
        '成本差': 110, '商品数量': 100, '实际成本': 120, '店铺优惠（分摊）': 160,
        '对外供货价（采集）': 170, '收货人手机号/提货人手机号': 200, '详细收货地址/提货地址': 200
      };
      return map[titleItem] || 150;
    },
    sortable(titleItem) {
      const sortItems = [
        '有赞成本价', '供货价（人工）', '供货价(人工)', '交易成功时间', '买家付款时间', '对外供货价（采集）', '对外供货价(采集)',
        '订单创建时间', '商品发货时间', '成本差', '商品实际成交金额', '商品单价', '商品金额小计', '店铺优惠(分摊)', '店铺优惠（分摊）',
        '商品已退款金额', '运费', '对外供货(采集)', '对外供货（采集）', '供货商品优惠', '商品优惠后价格', '实际成本'
      ];
      if (sortItems.indexOf(titleItem) >= 0) {
        return titleItem;
      } else {
        return false;
      }
    },
    // 归档状态初始化
    initArchivedStatus() {
      this.cancelDataToken && this.cancelDataToken.cancel('cancel');
      this.cancelStatisticsToken && this.cancelStatisticsToken.cancel('cancel');
      this.isInitArchive = true;
      this.statisticsLoading = false;
      this.filterInput = {};
      this.orderStatistics = {};
      this.getLastArchivedTime();
    },
    // 获取当前日期的前6个月的最后一天
    getLastArchivedTime() {
      this.lastArchivedTime = moment(new Date()).subtract(6, 'months').endOf('month').format('YYYY-MM-DD HH:mm:ss');
    },
    handleTabClick(id) {
      this.activeId = id;
      if (this.clearMixinSelection) this.clearMixinSelection();
      if (id === '已归档') {
        this.initArchivedStatus();
      } else {
        this.isInitArchive = false;
        this.getData(true);
      }
    },
    queryClick() {
      if (this.activeId === '已归档') {
        // 已归档如果没有筛选时间则不搜索数据
        let hasTimeFilter = false;
        const params = this.formatParams();
        ['createStart', 'payStartTime', 'dealStartTime', 'deliverGoodStart'].forEach(key => {
          if (params[key]) hasTimeFilter = true;
        });
        if (!hasTimeFilter) {
          this.isInitArchive = true;
          return;
        }
        this.isInitArchive = false;
      }
      this.getData(true);
    },
    queryEmpty() {
      this.isShowFilter = false;
      if (this.activeId === '已归档') {
        this.initArchivedStatus();
      } else {
        this.filterInput = {};
        this.queryClick();
      }
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      if (this.activeName !== '全部') params.orderStatus = this.activeName; // 设置tab
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      return params;
    },
    getData(reset = false, isPage = false) {
      this.cancelDataToken && this.cancelDataToken.cancel('cancel');
      const source = axios.CancelToken.source(); // 用于取消请求
      this.cancelDataToken = source;
      if (reset) {
        this.page = 1;
        if (this.clearMixinSelection) this.clearMixinSelection();
      }
      this.listLoading = true;
      const params = this.formatParams();
      this.uploadParams = params;
      getOrderList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          res.data.titles.push('操作');
          this.listData = res.data;
          this.listData.isInit = false;
          if (this.setSelectRow) this.setSelectRow(this.listData.items);
        }
      }).catch(e => {
        this.listLoading = false;
      });

      if (!isPage) this.getStatistics(params);
    },
    getStatistics(params) {
      this.statisticsLoading = true;
      this.cancelStatisticsToken && this.cancelStatisticsToken.cancel('cancel');
      const source = axios.CancelToken.source(); // 用于取消请求
      this.cancelStatisticsToken = source;
      getCommerceStatistics(params, source.token).then(res => {
        if (res.code === 200) {
          this.orderStatistics = res.data;
        }
        this.statisticsLoading = false;
      }).catch(e => {
        this.statisticsLoading = false;
      });
    },
    // 获取顶部Tab列表（订单状态）
    async getTabList() {
      try {
        const result = await getGoodsOrderStatus();
        const { code, data = [] } = result;
        if (code === 200) {
          // 只展示待结算、结算中的数量；
          data.forEach((tab) => {
            tab.num = tab.name === '待付款' || tab.name === '待发货' ? tab.num : 0;
            tab.id = tab.name;
          });
          this.tabList = data;
        }
      } catch (error) {
        this.tabList = [
          { id: '全部', name: '全部', num: 0 },
          { id: '待付款', name: '待付款', num: 0 },
          { id: '待发货', name: '待发货', num: 0 },
          { id: '已发货', name: '已发货', num: 0 },
          { id: '已完成', name: '已完成', num: 0 },
          { id: '已关闭', name: '已关闭', num: 0 }
        ];
        console.log(error);
      }
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getData(true, true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getData(false, true);
    },
    // 导出订单
    exportBeforeExport() {
      this.uploadParams.orderNums = this.ids;
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(this.uploadParams, 'projectExportRef');
      }
    },
    // 自动关联
    autoAssociation() {
      autoAssociation().then(res => {
        if (res.code === 200) {
          this.associationMessage = res.message;
          this.associationVisible = true;
        }
      }).catch(err => {
        console.error(err.message);
      });
    },
    // 批量确认商品
    goodsBatchConfirm(orderNum = '', item = []) {
      let result = true;
      if (!orderNum && !this.ids) {
        this.$message.warning('请勾选需要确认商品的订单');
        return false;
      }
      if (!orderNum && this.ids) {
        const selectArr = this.specificationCodeIdLists.split(',');
        const flag = selectArr[0];
        result = selectArr.every(i => i === flag);
      }
      if (!result) {
        this.$message.warning('请选择商品规格ID相同的订单');
        return false;
      }
      const goodsIdIndex = this.getTitleIndex('商品ID');
      const codeIdIndex = this.getTitleIndex('商品规格ID');
      if (orderNum) { // orderNums 以前只传的订单号，现在需要用"|"线拼接一下 商品规格ID 和 商品ID
        this.selectOrderNums = `${orderNum}|${item[codeIdIndex]}|${item[goodsIdIndex]}`;
      } else {
        const numbs = [];
        this.multipleSelectionAll.map(el => {
          numbs.push(`${el[0]}|${el[codeIdIndex]}|${el[goodsIdIndex]}`);
        });
        this.selectOrderNums = numbs.join(',');
      }
      // 单个订单关联
      // 商品ID和商品规格ID必须填写一个
      this.goodsId = goodsIdIndex ? (item[goodsIdIndex] || item[goodsIdIndex] === '' || item[goodsIdIndex] === null ? item[goodsIdIndex] : this.selectList[0][goodsIdIndex]) : '';
      this.specificationCodeId = codeIdIndex ? (item[codeIdIndex] || item[codeIdIndex] === '' || item[codeIdIndex] === null ? item[codeIdIndex] : this.selectList[0][codeIdIndex]) : '';
      if (!this.goodsId && !this.specificationCodeId) {
        this.$message.warning('请确认订单的“商品id”或“商品规格ID”后进行商品关联');
        return false;
      }
      this.orderItem = this.selectList.length === 1 ? this.selectList[0] : item;
      this.goodsId = this.selectList.length > 1 ? '' : this.goodsId;
      this.dialogGoodsConfirmVisible = true;
    },
    // 多选
    tableSelectionChange(e) {
      this.selectList = e;
      const codeIdIndex = this.getTitleIndex('商品规格ID');
      this.ids = e.map(i => i[0]).join(',');
      this.specificationCodeIdLists = e.map(i => i[codeIdIndex]).join(',');
    },
    closeDialog() {
      this.dialogGoodsConfirmVisible = false;
    },
    handleSuccess(type) {
      this.dialogGoodsConfirmVisible = false;
      this.getData(true);
    },
    tableRowClassName({ row, rowIndex }) {
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[0]);
        return ids.includes(row[0]) ? 'table-selected' : '';
      }
      return '';
    },
    includesPriceField(filed) {
      const priceField = [
        '商品实际成交金额', '商品已退款金额', '有赞成本价', '供货价（人工）',
        '成本差', '对外供货价', '商品单价', '商品优惠后价格', '商品金额小计', '店铺优惠（分摊）', '实际成本',
        '运费', '供货商品优惠'
      ];
      return priceField.some(i => filed.indexOf(i) >= 0);
    },
    isPriceKeyword(name) {
      const arr = ['有赞成本价', '供货价（人工）'];
      return this.includesPriceField(name) || arr.some(i => name.indexOf(i) >= 0);
    },
    goFreshOrder() {
      this.$router.push({
        name: 'commerceOrderFresh'
      });
    },
    getLogText(row, column) {
      return `有赞订单 ${row[0]} 的 ${column.label}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.product-container {
  margin: 16px 16px 0 16px;
  // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  // border-radius:12px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
  ::v-deep {
    .display-none .cell {
      max-width: 1px;
      max-height: 20px;
      overflow: hidden;
    }
  }
  .batch-set {
    padding: 7px 12px;
    font-size: 14px;
    color: #666666;
    height: 32px;
    background-color: #fff;
    border: 1px solid #DDDDDD;
  }
}
.list-top {
  display: flex;
  align-items: center;
  .btn-right {
    display: flex;
    align-items: center;
  }
}
.overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.coustom-select-width {
  & ::v-deep {
    .el-input__inner {
      width: 140px !important;
    }
  }
}
.btn-right-item {
  font-size: 14px;
  margin: 0;
  ::v-deep {
    .medium-import-btn {
      padding: 7px 10px;
      border-color: #406EFF;
      border-radius: 3px;
      font-size: 14px;
      color: #fff;
      background-color: #406EFF;
    }
  }
}
.flex {
  display: flex;
  align-items: center;
}
.dot {
  display: inline-block;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 6px;
}
.green {
  color: #31cc9c;
}
.red {
  color: #FF504F;
}
.dropdown-wrap {
  margin-top: -24px;
  margin-right: 15px;
  padding: 0;
  .el-dropdown-menu__item {
    width: 100px;
    text-align: center;
  }
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.init-archive {
  padding-top: 50px;
  font-size: 14px;
  color: #333;
  text-align: center;
  .tip {
    width: 64px;
  }
  p {
    margin: 0;
    text-align: center;
    &:first-of-type {
      margin: 14px 0 8px;
      font-size: 16px;
      font-weight: bold;
    }
    &:last-of-type {
      color: #999;
    }
  }
}
.mobile-table {
  &::v-deep {
    .el-pagination {
      padding: 2px 5px !important;
    }
  }
}
.task-dialog {
  ::v-deep .el-dialog {
    border-radius: 12px;
  }
  ::v-deep .el-dialog__body {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-flow: column nowrap;
    padding: 0 25px;
    .el-button {
      margin: 6px 0 4px;
    }
  }
  ::v-deep .el-dialog__footer {
    padding: 16px 0 24px;
  }
  .task-message {
    font-size: 16px;
    font-family: PingFangSC-Medium;
    text-align: center;
    color: #333333;
    line-height: 20px;
  }
  img {
    width: 140px;
  }
}
</style>
<style lang="scss">
.el-dropdown-menu-batch-set {
  margin-bottom: 5px;
  padding: 0;
  .btn-right-item {
    margin: 0 !important;
    padding: 0;
    .el-button span {
      color: #666;
      font-weight: normal;
      &:hover {
        color: #668bff;
      }
    }
  }
  .el-dropdown-menu__item {
    padding: 0 10px;
    min-width: 100px;
    text-align: center;
  }
  .meidum-export-btn, .el-button {
    margin-right: 0px;
    padding: 10px 14px !important;
    border: none;
    height: 36px;
    color: inherit;
    background: none;
  }
}
</style>

